<template>
    <pre v-html="jsonHtml"></pre>
</template>

<script>
    export default {
      name: "ShowJsonDesc",
      props: {
        jsonObject: {
          type: Object,
          required: true
        }
      },
      data () {
        return {
          jsonHtml: ""
        }
      },
      created () {
        this.jsonHtml = this.syntaxHighlight(this.jsonObject);
      },
      methods: {
        /**通过JSON对象在页面上显示JSON格式的数据结构**/
        syntaxHighlight(json) {
          if (typeof json != 'string') {
            json = JSON.stringify(json, undefined, 4);
          }
          json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
          return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
            let cls = 'hint-number';
            if (/^"/.test(match)) {
              if (/:$/.test(match)) {
                cls = 'key';
              } else {
                cls = 'string';
              }
            } else if (/true|false/.test(match)) {
              cls = 'boolean';
            } else if (/null/.test(match)) {
              cls = 'null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
          });
        }
      }
    }
</script>

<style>
  pre {padding: 5px;height: 100%;font-size: 12px;font-family: '\5FAE\8F6F\96C5\9ED1'; }
  .string { color: #999; }
  .hint-number { color: darkorange; }
  .boolean { color: blue; }
  .null { color: magenta; }
  .key { color: #333;cursor: pointer;line-height: 2.5; }
  .key:hover .name{color: #9cb945;}
  .type { color: red; }
</style>
